/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.fgv.util;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 * Hibernate Utility class with a convenient method to get Session Factory
 * object.
 *
 * @author adao
 */
public class HibernateUtil {

    private static final SessionFactory factory;
    private static final ThreadLocal sessionThread = new ThreadLocal();
    private static final ThreadLocal transactionThread = new ThreadLocal();
    private static Logger log = Logger.getLogger(HibernateUtil.class.getName());

    public static Session getSession() {
        Session session = (Session) sessionThread.get();
        if ((session == null) || (!(session.isOpen()))) {
            log.info("Iniciando conexão ...");

            session = factory.openSession();
            sessionThread.set(session);

            log.info("Conexão inicializada ...");

        }
        return ((Session) sessionThread.get());
    }

    public static SessionFactory getSessionFactory() {
        return factory;
    }

    public static void closeSession() {
        Session session = (Session) sessionThread.get();
        if ((session != null) && (session.isOpen())) {
            log.info("iniciar fechamento conexão...");

            sessionThread.set(null);
            session.close();

            log.info("conexão fechada...");

        }
    }

    public static void beginTransaction() {
        log.info("iniciando  transação...");

        Transaction transaction = getSession().beginTransaction();
        transactionThread.set(transaction);

        log.info("transação inicializada...");

    }

    public static void commitTransaction() {
        Transaction transaction = (Transaction) transactionThread.get();
        if ((transaction != null) && (!(transaction.wasCommitted())) && (!(transaction.wasRolledBack()))) {
            log.info("iniciando  commit...");

            transaction.commit();
            transactionThread.set(null);

            log.info("Commit realizado...");
        }

    }

    public static void rollbackTransaction() {

        Transaction transaction = (Transaction) transactionThread.get();

        if ((transaction != null) && (!(transaction.wasCommitted())) && (!(transaction.wasRolledBack()))) {
            log.info("iniciando  rollback...");

            transaction.rollback();
            transactionThread.set(null);

            log.info("Rollback  Realizado...");

        }

    }

    static {

        // Create the SessionFactory from standard (hibernate.cfg.xml) config file.
        AnnotationConfiguration ac = new AnnotationConfiguration();
        factory = ac.configure().buildSessionFactory();

        BasicConfigurator.configure();
    }

    public static void cancelar() {
        log.info("Iniciando Cancelar  ...");

        HibernateUtil.rollbackTransaction();

        log.info("Cancelar  Realizado...");

    }

    public static void main(String[] args) {
        log.info("Iniciando main()  ...");
    }
}